﻿using Crawler.Core.EventBus;
using Crawler.IRepositories;
using Crawler.Model.SystemDefault;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Crawler.Common.Net;
using Crawler.IRepositories.SystemDefault;
using Crawler.Core.CrawlerHandler.Analyzer;
using Crawler.Common;

namespace Crawler.Core.CrawlerHandler.Collector
{
    public class CollectorHandler : IEventHandler<CollectorEventEntity>
    {
        private readonly IRepository<CollectInfoConfigModel> collectInfoConfigRepository;
        private readonly IRepository<TerminalConfigModel> terminalConfigRepository;
        private readonly IServiceProvider serviceProvider;
        private List<Task> collectTasks;

        public CollectorHandler(
            IRepository<CollectInfoConfigModel> collectInfoConfigRepository
            , IRepository<TerminalConfigModel> terminalConfigRepository
            , IServiceProvider serviceProvider
            )
        {
            this.collectInfoConfigRepository = collectInfoConfigRepository;
            this.terminalConfigRepository = terminalConfigRepository;
            this.serviceProvider = serviceProvider;
            collectTasks = new List<Task>();
        }

        public void Trigger(CollectorEventEntity entity)
        {
            var urlModel = entity.collectorUrlModel;
            if (urlModel == null || urlModel.CollectStatus == CollectStatus.Collected) return;


            //获取配置信息
            var configModel = collectInfoConfigRepository.Find(urlModel.CollectorConfigID);
            //配置设置停止则终止
            if (configModel == null || configModel.WorkStatus != WorkStatus.Running)
            {
                //Console.WriteLine("+++++Collector Stop");
                return;
            }
            //获取终端配置
            var terminalConfig = terminalConfigRepository.Find(Constant.AppSetting.TerminalId);

            //判断是否开启了新的一次抓取
            if (configModel.LatestCollectTime > urlModel.AddTime) return;

            //默认休息 避免把人家服务器搞死
            Thread.Sleep(terminalConfig.Frequency < 300 ? 300 : terminalConfig.Frequency);

            var taskData = new object[] { configModel, urlModel };
            collectTasks.Add(Task.Factory.StartNew(state =>
            {
                var data = state as object[];
                CollectInfoConfigModel _configModel = data[0] as CollectInfoConfigModel;
                CollectorUrlModel _urlModel = data[1] as CollectorUrlModel;
                var collectTaskHandler = (CollectTaskHandler)serviceProvider.GetService(typeof(CollectTaskHandler));
                collectTaskHandler.Collect(terminalConfig, _configModel, _urlModel);

            }, taskData));

            //开多线程取采集,限制一下不要太多
            if (terminalConfig.MutiTaskCount < 0)
                terminalConfig.MutiTaskCount = 0;
            if (terminalConfig.MutiTaskCount >= 30)
                terminalConfig.MutiTaskCount = 30;
            if (collectTasks.Count > terminalConfig.MutiTaskCount)
            {
                collectTasks = collectTasks.Where(t => !t.IsCanceled && !t.IsCompleted && !t.IsFaulted).ToList();
                Task.WaitAny(collectTasks.ToArray());
            }

        }
    }
}
